package com.tmpt.freemarker.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 * Created by wxy on 2017/1/26.
 */
public class FreemarkerUtils {
    private String pathFtl ;
    private String pathJsp ;

    public FreemarkerUtils(String pathFtl,String pathJsp){
        this.pathFtl = pathFtl;
        this.pathJsp = pathJsp;
    }

    public Template getTemplate(String name){
        try{
            Configuration cfg = new Configuration();
            //cfg.setClassForTemplateLoading(this.getClass(),"E:\\freemarker\\");
            //cfg.setDirectoryForTemplateLoading(new File("E:\\freemarker\\"));
            cfg.setDirectoryForTemplateLoading(new File(pathFtl));
            cfg.setDefaultEncoding("UTF-8");
            Template temp = cfg.getTemplate(name);
            return temp;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void print(String name, Map<String,Object> root){
        try {
            Template temp = this.getTemplate(name);
            temp.process(root, new PrintWriter(System.out));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void fprint(String name, Map<String,Object> root, String outFile){
        FileWriter out = null;
        try{
            System.out.println("0000000000000000000000000000000="+pathJsp);
            File file = new File(pathJsp);
            if(!file.exists()){
                file.mkdir();
            }
            //out = new FileWriter(new File(pathJsp+outFile));
            OutputStreamWriter out2 = new OutputStreamWriter(new FileOutputStream(pathJsp+outFile),"UTF-8");
            Template temp = this.getTemplate(name);
            temp.process(root,out2);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(out!=null)out.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }


}
